    //
    //  EJSHomeGoodCollectionViewCell.m
    //  FlyFish
    //
    //  Created by 海丰丛 on 2019/4/7.
    //  Copyright © 2019 lifayu. All rights reserved.
    //

#import "EJSHomeGoodCollectionViewCell.h"
#import "EJSGoodsModel.h"
#import "EJSShoppingCartListRequest.h"
#import "EJSUpdateShopCartRequest.h"
#import "EJSGoodsAddCartRequest.h"
#import "EJSGoodsDetailInfoRequest.h"
#import "EJSSelectGoodsSpecView.h"
#import "JSONKit.h"
#import <SVProgressHUD.h>
#import "XOShoppingCartModel.h"
#import "XOShoppingCartListModel.h"
#import "XOShoppingCartListRequest.h"
#import "XOShopViewModel.h"
#import "EJSLoginViewController.h"

@interface EJSHomeGoodCollectionViewCell ()

@property (strong, nonatomic) EJSGoodsSkuModel *selectSkuModel;
@property (strong, nonatomic) EJSShoppingCartGoodsModel *currentCartModel;
StrongProperty NSMutableArray *cartGoodsModels;
StrongProperty EJSGoodsModel *detailGoodModel;
AssignProperty NSInteger addedGoodsCount;

@end
@implementation EJSHomeGoodCollectionViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
        // Initialization code

    [self setShadowWith:self.addButton];
    [self setShadowWith:self.reAddButton];
    [self setShadowWith:self.removeButton];
    [self setShadowWith:self.deleteButton];
}

- (void) setShadowWith: (UIView *)element {
    element.layer.cornerRadius = 16;
    element.layer.borderColor = AppMainColor.CGColor;
    element.layer.borderWidth = 0.5;
    element.layer.shadowColor = AppMainColor.CGColor;
    element.layer.shadowRadius = 2;
    element.layer.shadowOpacity = 0.6;
    element.layer.shadowOffset = CGSizeMake(0, 1);
}
#pragma mark - loadData
- (void)getCartList{
    if(![EJSUserTokenModel userTokenModel]){
        return;
    }
    FlyWeakSelf
    [[XOShopCartViewModel shared] updateCartList:^(XOShoppingCartListModel * _Nonnull response) {
        XOShoppingCartListModel *cartList = response;
        for (XOShoppingCartModel *cart in cartList.list) {
            if ([cart.shopId isEqualToString: [XOShopViewModel shared].shopId]) {
                _shoppingCartListModel = cart;
                [weakSelf checkGoodInCartCount: cart];
            }
        }
        if (self.delegate && [weakSelf.delegate respondsToSelector:@selector(homeGoodUpdateShopCartWith:)]) {
            [weakSelf.delegate homeGoodUpdateShopCartWith:weakSelf.shoppingCartListModel];
        }
    }];

}

- (void) checkGoodInCartCount: (XOShoppingCartModel *) model {
    NSMutableArray *tempCartModel = [NSMutableArray new];
    NSInteger tempNumber = 0;
    for (EJSShoppingCartGoodsModel * good in model.carts) {
        if (good.spuId == self.goodModel.spuId) {
            tempNumber += good.num.integerValue;
            [tempCartModel addObject:good];
        }

        if (tempCartModel.count == 1) {
             self.currentCartModel = tempCartModel.lastObject;
        }else {
            self.cartGoodsModels = tempCartModel;
        }
        self.goodInCartNumber = tempNumber;
    }
}

- (void)getGoodsDetailInfo{
    EJSGoodsDetailInfoRequest *req = [[EJSGoodsDetailInfoRequest alloc] init];
    req.spuId = self.goodModel.spuId;
    req.hideLoadingView = YES;
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        self.detailGoodModel = response.data;
        [self AddToShoppingCart];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

- (void)AddToShoppingCart {
    if (_delegate && [_delegate respondsToSelector:@selector(homeGoodCellIsLogin)]) {
        if ([_delegate homeGoodCellIsLogin]) {
            if(_goodModel.hasDefaultSku.integerValue == 1 && _goodModel.skus.count > 0){
                self.selectSkuModel = _goodModel.skus.firstObject;
                self.selectSkuModel.skuSelectCount = _goodModel.minToBuy.integerValue;
                [self addToCartReq:self.selectSkuModel];
                return;
            }
            FlyWeakSelf
            [EJSSelectGoodsSpecView showSelectGoodsSpecView:_goodModel completion:^(EJSGoodsSkuModel *selectSkuModel) {
                self.selectSkuModel = selectSkuModel;
                [weakSelf addToCartReq:selectSkuModel];
            }];
        }
    }
}

- (void)addToCartReq:(EJSGoodsSkuModel *)skuModel{
    EJSGoodsAddCartRequest *req = [[EJSGoodsAddCartRequest alloc] init];
    req.skuId = skuModel.skuId;
    req.num = @(skuModel.skuSelectCount).stringValue;
    req.hideLoadingView = YES;
    FlyWeakSelf
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        if(weakSelf.selectSkuModel){
            weakSelf.selectSkuModel = nil;
        }
        [weakSelf getCartList];

    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

- (void)updateShopCartRequestWithFlag:(int)flag {
    NSMutableArray *datas = [NSMutableArray array];

    if (_currentCartModel) {
        _currentCartModel.num = [@(_goodInCartNumber) stringValue];
    }

    for (EJSShoppingCartGoodsModel *goodsModel in self.shoppingCartListModel.carts) {
        if (goodsModel.spuId == _currentCartModel.spuId && _currentCartModel.num.intValue > 0) {
            goodsModel.num = _currentCartModel.num;
        }
        EJSUpdateShopCartModel *model = [EJSUpdateShopCartModel new];
        model.cart_id = goodsModel.cartId;
        model.sku_id = goodsModel.spuId;
        model.num = goodsModel.num;
        [datas addObject:[model getJsonDictionary]];
    }

    EJSUpdateShopCartRequest *req = [[EJSUpdateShopCartRequest alloc] init];
    req.hideLoadingView = YES;
    req.data = [datas JSONString];
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {

        if (flag == 1) {
            [self showAnimationWithDelete];
        }
        if (flag == 2) {
            [self showAnimationWithReAdd];
        }
        if (flag == 3 && self.goodInCartNumber > 0 && self.goodInCartNumber <= [self.goodModel.minToBuy integerValue]) {
            [self showAnimationWithRemove];
        }
        [self getCartList];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

- (void)setCurrentCartModel:(EJSShoppingCartGoodsModel *)currentCartModel {
    _currentCartModel = currentCartModel;
}

- (void)setGoodInCartNumber:(NSInteger)goodInCartNumber {
    _goodInCartNumber = goodInCartNumber;
    _goodModel.addCartNum = [NSNumber numberWithInteger:goodInCartNumber];
    if (goodInCartNumber == 0) {
        return;
    }
    if (!(goodInCartNumber / _goodModel.minToBuy.intValue > 1)) {
        [self showAnimationWihtAdd];
    }else {
        [self showAnimationWithReAdd];
    }
}

- (void)setShoppingCartListModel:(XOShoppingCartModel *)shoppingCartListModel {

    _shoppingCartListModel = shoppingCartListModel;
    _goodInCartNumber = 0;
    _currentCartModel = nil;
    _addButton.alpha = 1.0;
    _reAddButton.alpha = 1.0;
    _removeButton.alpha = 1.0;
    _deleteButton.alpha = 1.0;

    NSMutableArray *tempCarts = [NSMutableArray new];
    NSInteger tempNumber = 0;
    for (EJSShoppingCartGoodsModel *cartModel in _shoppingCartListModel.carts) {
        if ([cartModel.spuId integerValue] == [_goodModel.spuId integerValue]) {
            tempNumber  += [cartModel.num integerValue];
            _currentCartModel = cartModel;
            [tempCarts addObject:cartModel];
        }
    }
    _goodInCartNumber = tempNumber;
    _cartGoodsModels = tempCarts;

    CGFloat tW = (self.width - 40 )/2.0;
    if (_goodInCartNumber == 0) {
        self.nameLabel.numberOfLines = 3;
        self.cartViewHeightConstraint.constant = 0;
        self.addButtonLeftConstraint.constant = 15;
        [self.deleteButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(-4-tW/2.0);
            make.centerY.mas_equalTo(-3.5);
            make.height.mas_equalTo(1);
            make.width.mas_equalTo(1);
        }];
        [self.removeButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(-4-tW/2.0);
            make.centerY.mas_equalTo(-3.5);
            make.height.mas_equalTo(1);
            make.width.mas_equalTo(1);
        }];
    }else if (_goodInCartNumber <= [_goodModel.minToBuy integerValue]) {
        self.cartViewHeightConstraint.constant = 37;
        self.addButtonLeftConstraint.constant = (ScreenWidth/2.0 - 38)/2.0 + 23;
        self.nameLabel.numberOfLines = 1;

        [self.deleteButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(-4-tW/2.0);
            make.centerY.mas_equalTo(-3.5);
            make.height.mas_equalTo(32);
            make.width.mas_equalTo(tW);
        }];
        [self.reAddButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-15);
            make.bottom.mas_equalTo(-15);
            make.height.mas_equalTo(32);
            make.width.mas_equalTo(tW);
        }];

    }else if (_goodInCartNumber > [_goodModel.minToBuy integerValue]) {
        self.cartViewHeightConstraint.constant = 37;
        self.addButtonLeftConstraint.constant = (ScreenWidth/2.0 - 38)/2.0 + 23;
        self.nameLabel.numberOfLines = 1;

        [self.removeButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(-4-tW/2.0);
            make.centerY.mas_equalTo(-3.5);
            make.height.mas_equalTo(32);
            make.width.mas_equalTo(tW);
        }];

        [self.reAddButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-15);
            make.bottom.mas_equalTo(-15);
            make.height.mas_equalTo(32);
            make.width.mas_equalTo(tW);
        }];

    }
    [self.coverView layoutIfNeeded];
    [self goodIncartNumber:_goodInCartNumber];
}

- (void)setGoodModel:(EJSGoodsModel *)goodModel {
    _goodModel = goodModel;
    self.nameLabel.text = _goodModel.spuName;
    self.priceLabel.text = [NSString stringWithFormat:@"€ %@",_goodModel.price];
    NSString *unid = [NSString stringWithFormat: @"%@ / %@", _goodModel.minToBuy, _goodModel.unit?_goodModel.unit:@"件"];
    self.udLabel.text = unid;
    [self.iconView setImageWithUrl:_goodModel.cover];
    self.cartViewHeightConstraint.constant = 0;
}

- (void)goodIncartNumber:(NSInteger)number {

    self.cartNumberLabel.text = [@(number / _goodModel.minToBuy.integerValue) stringValue];

    if (number == 0) {
        self.addButton.hidden = NO;
        self.reAddButton.hidden = YES;
        self.deleteButton.hidden = YES;
        self.removeButton.hidden = YES;
        return;
    }
    if (number <= [_goodModel.minToBuy integerValue]) {
        self.addButton.hidden = YES;
        self.reAddButton.hidden = NO;
        self.deleteButton.hidden = NO;
        self.removeButton.hidden = YES;
        return;
    }

    self.addButton.hidden = YES;
    self.reAddButton.hidden = NO;
    self.deleteButton.hidden = YES;
    self.removeButton.hidden = NO;

}

- (IBAction)buttonAction:(UIButton *)sender {
    
    if (![self.delegate respondsToSelector:@selector(homeGoodCellIsLogin)]) {
        return;
    }

    if ([sender isEqual:_addButton] || [sender isEqual:_reAddButton]) {
        [self AddToShoppingCart];
    }

    if ([sender isEqual:_deleteButton]) {
        _goodInCartNumber = 0;
        NSMutableArray *cartsArr = [_shoppingCartListModel.carts mutableCopy];
        [cartsArr removeObject:_currentCartModel];
        _shoppingCartListModel.carts = cartsArr;
        [self updateShopCartRequestWithFlag:1];

    }

    if ([sender isEqual:_removeButton]) {
        if (self.cartGoodsModels.count > 1) {
            if (self.delegate && [self.delegate respondsToSelector:@selector(homeGoodCellWillShowCartView:andCurrentSpuId:)]) {
                [self.delegate homeGoodCellWillShowCartView:_shoppingCartListModel andCurrentSpuId:_currentCartModel.spuId];
            }
        }else {
            _goodInCartNumber -= _goodModel.minToBuy.integerValue;
            _currentCartModel.num = [@([_currentCartModel.num integerValue] - _goodModel.minToBuy.integerValue) stringValue];
            [self updateShopCartRequestWithFlag:3];
        }
    }

}



#pragma mark - 执行动画
    // 1
- (void)showAnimationWihtAdd {
    FlyWeakSelf
    CGFloat tW = (self.width - 40 )/2.0;
    self.cartViewHeightConstraint.constant = 37;
    self.addButtonLeftConstraint.constant = (ScreenWidth/2.0 - 38)/2.0 + 23;
    [UIView animateWithDuration:0.2 animations:^{
        weakSelf.addButton.alpha = 0.0;
        weakSelf.reAddButton.alpha = 1.0;
        weakSelf.deleteButton.alpha = 1.0;
        weakSelf.nameLabel.numberOfLines = 1;
        weakSelf.cartNumberLabel.text = weakSelf.currentCartModel.num;
        [weakSelf.deleteButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(-4-tW/2.0);
            make.centerY.mas_equalTo(-3.5);
            make.height.mas_equalTo(32);
            make.width.mas_equalTo(tW);
        }];
        [weakSelf.reAddButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-15);
            make.bottom.mas_equalTo(-15);
            make.height.mas_equalTo(32);
            make.width.mas_equalTo(tW);
        }];
        [weakSelf.coverView layoutIfNeeded];
    } completion:^(BOOL finished) {
        [weakSelf goodIncartNumber:_goodInCartNumber];
    }];
}

- (void)showAnimationWithDelete {
    FlyWeakSelf
    CGFloat tW = (self.width - 40 )/2.0;
    self.cartViewHeightConstraint.constant = 0;
    self.addButtonLeftConstraint.constant = 15;
    self.addButton.hidden = NO;
    self.addButton.alpha = 0;
    [UIView animateWithDuration:0.2 animations:^{
        weakSelf.addButton.alpha = 1.0;
        weakSelf.reAddButton.alpha = 0.0;
        weakSelf.deleteButton.alpha = 0.0;

        [weakSelf.deleteButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(-4-tW/2.0);
            make.centerY.mas_equalTo(-3.5);
                //                make.bottom.mas_equalTo(-15);
            make.height.mas_equalTo(1);
            make.width.mas_equalTo(1);
        }];
        [weakSelf.reAddButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-15);
            make.bottom.mas_equalTo(-15);
            make.height.mas_equalTo(32);
            make.width.mas_equalTo(ScreenWidth/2.0-30);
        }];

        [weakSelf.coverView layoutIfNeeded];

    } completion:^(BOOL finished) {
        weakSelf.nameLabel.numberOfLines = 3;
        [weakSelf goodIncartNumber:weakSelf.goodInCartNumber];
    }];
}

- (void)showAnimationWithReAdd {
    FlyWeakSelf
    CGFloat tW = (self.width - 40 )/2.0;
    self.removeButton.hidden = NO;
    [UIView animateWithDuration:0.2 animations:^{
        weakSelf.nameLabel.numberOfLines = 1;
        [weakSelf.removeButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(-4-tW/2.0);
            make.centerY.mas_equalTo(-3.5);
            make.height.mas_equalTo(32);
            make.width.mas_equalTo(tW);
        }];
        [weakSelf.coverView layoutIfNeeded];

    } completion:^(BOOL finished) {
        [weakSelf goodIncartNumber: _goodInCartNumber];
    }];
}

- (void)showAnimationWithRemove {
    FlyWeakSelf
    CGFloat tW = (self.width - 40 )/2.0;
    [UIView animateWithDuration:0.2 animations:^{
        weakSelf.nameLabel.numberOfLines = 1;
        [weakSelf.removeButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(-4-tW/2.0);
            make.centerY.mas_equalTo(-3.5);
            make.height.mas_equalTo(1);
            make.width.mas_equalTo(1);
        }];

        [weakSelf.coverView layoutIfNeeded];

    } completion:^(BOOL finished) {
        [weakSelf goodIncartNumber:weakSelf.goodInCartNumber];
    }];
}

@end
